package com.zdzx.controller.web;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.ArticleMapper;
import com.zdzx.mapper.ArticleWatchMapper;
import com.zdzx.mapper.DicMapper;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.Dic;
import com.zdzx.model.service.content.result.ArticleInfo;
import com.zdzx.model.service.content.vo.Article;
import com.zdzx.model.service.content.vo.ArticleWatch;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "web文章")
@RestController()
@RequestMapping("/web")
public class WebArticleController {

	
	@Autowired
	private DicMapper dicMapper;
	@Autowired
	private ArticleMapper articleMapper;
	@Autowired
	private ArticleWatchMapper articleWatchMapper;
	@Autowired
	private RedisUtil redisUtil;

	@ApiOperation(value = "首页分类", notes = "")
	@GetMapping("/article/article-type")
	public Result<List<Dic>> articleType(@RequestParam("tenantId") String tenantId) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`type`", "article");
		if(!StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", StringUtils.isEmpty(tenantId) ? "00000000" : tenantId);
		}
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}
	
	@ApiOperation(value = "法律法规分类", notes = "")
	@GetMapping("/article/flfg-type")
	public Result<List<Dic>> flfgType(@RequestParam(value="tenantId", required = false) String tenantId) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`type`", "flfg");
		queryWrapper.eq("tenant_id", StringUtils.isEmpty(tenantId) ? "00000000" : tenantId);
		queryWrapper.orderByAsc("`index`");
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}
	
	@ApiOperation(value = "地方性规范分类", notes = "")
	@GetMapping("/article/dfxfg-type")
	public Result<List<Dic>> dfxfgType(@RequestParam(value="tenantId", required = false) String tenantId) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`type`", "dfxfg");
			queryWrapper.eq("tenant_id", StringUtils.isEmpty(tenantId) ? "00000000" : tenantId);
		
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}
	@ApiOperation(value = "规范性文件分类", notes = "")
	@GetMapping("/article/gfxwjf-type")
	public Result<List<Dic>> gfxwjfType(@RequestParam(value="tenantId", required = false) String tenantId) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`type`", "gfxwjf");
			queryWrapper.eq("tenant_id", StringUtils.isEmpty(tenantId) ? "00000000" : tenantId);
		
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}

	@ApiOperation(value = "分类文章", notes = "")
	@GetMapping("/article")
	public Result<PageInfo<Article>> article(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("0行业标准  1国家标准") @RequestParam(value = "standardType", required = false) String standardType,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("文章类型") @RequestParam(value = "type", required = false) String type,
			@ApiParam("法律法规类型") @RequestParam(value = "flfgType", required = false) String flfgType,
			@ApiParam("地方性法规类型") @RequestParam(value = "dfxfgType", required = false) String dfxfgType,
			@ApiParam("规范性文件类型") @RequestParam(value = "gfxwjfType", required = false) String gfxwjfType,
			@ApiParam("0 编辑  1pdf") @RequestParam(value = "isShow", required = false) String isShow,
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId) {
		type=StringUtils.isEmpty(type) ? "notice" : type;
		if(!StringUtils.isEmpty(title)) {
			type="";
		}
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<Article> page = new Page<>(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
		QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("create_time");
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
		if(!StringUtils.isEmpty(isShow)) {
			queryWrapper.eq("is_show", isShow);
		}
		if (StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", "00000000");
		}else {
			queryWrapper.eq("tenant_id",tenantId);
		}
		if (!StringUtils.isEmpty(type) && !"0".equals(type)) {
			queryWrapper.eq("type", type);
			if(type.equals("dabz")) {
				if(StringUtils.isEmpty(standardType))
					queryWrapper.eq("standard_type", "0");
				else
					queryWrapper.eq("standard_type", standardType);
			}else if(type.equals("flfg")) {
				if(!StringUtils.isEmpty(flfgType) &&flfgType.equals("dfxfg")) {
					queryWrapper.eq("dfxfg_type", dfxfgType);
				}else if(!StringUtils.isEmpty(flfgType) &&flfgType.equals("gfxwjf")){
					queryWrapper.eq("gfxwjf_type", gfxwjfType);
				}else {
					if(!StringUtils.isEmpty(flfgType)) {
						queryWrapper.eq("flfg_type", flfgType);
					}
				}
			}
		}
		
		queryWrapper.select("id","title","title_image","`desc`","views","create_time");
		IPage<Article> info = articleMapper.selectPage(page, queryWrapper);
		PageInfo<Article> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}

	@ApiOperation(value = "查询详情", notes = "")
	@GetMapping("/article/{articleId}")
	public Result<ArticleInfo> webDetails(@PathVariable("articleId") String articleId,
			@ApiParam("") @RequestParam(value = "t", required = false) String tenantId,
			HttpServletRequest request){
		ArticleInfo info=new ArticleInfo();
		Article article = articleMapper.selectById(articleId);
		if(article!=null) {
			info.setArticle(article);
			String ip = "";
			if(request.getHeader("x-forwarded-for") == null) {
				ip = request.getRemoteAddr();
			}else{
				ip = request.getHeader("x-forwarded-for");
			}
			
			Page<Article> page=new Page<Article>(1, 1);
			
			QueryWrapper<Article> queryWrapperPre=new QueryWrapper<Article>();
			queryWrapperPre.gt("create_time", article.getCreateTime());
			queryWrapperPre.orderByAsc("create_time");
			queryWrapperPre.select("id","title");
			queryWrapperPre.eq("`type`", article.getType());
			queryWrapperPre.eq("`tenant_id`", StringUtils.isEmpty(tenantId)?"00000000":tenantId);
			IPage<Article> pre = articleMapper.selectPage(page, queryWrapperPre);
			info.setPre((pre!=null&&pre.getRecords().size()>0)?pre.getRecords().get(0):null);
			
			QueryWrapper<Article> queryWrapperNext=new QueryWrapper<Article>();
			queryWrapperNext.lt("create_time", article.getCreateTime());
			queryWrapperNext.orderByDesc("create_time");
			queryWrapperNext.eq("`type`", article.getType());
			queryWrapperNext.select("id","title");
			queryWrapperNext.eq("`tenant_id`", StringUtils.isEmpty(tenantId)?"00000000":tenantId);
			IPage<Article> next = articleMapper.selectPage(page, queryWrapperNext);
			info.setNext((next!=null&&next.getRecords().size()>0)?next.getRecords().get(0):null);
			
			
			String views = (String)redisUtil.get(articleId+":"+ip);
			if(StringUtils.isEmpty(views)){
			redisUtil.set(articleId+":"+ip,"0",getMiao());
				Article entity=new Article();
				entity.setId(articleId);
				entity.setViews((article.getViews()==null?0:article.getViews())+1);
				articleMapper.updateById(entity);
			}
			}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), ResultCode.RESULT_SUCCESS.getMes(), info);
	}
	
	

	@ApiOperation(value = "企业分类", notes = "")
	@GetMapping("/{enterpriseId}/article-type")
	public Result<List<Dic>> enterpriseArticleType(
			@PathVariable("enterpriseId") String enterpriseId) {
		QueryWrapper<Dic> queryWrapper=new QueryWrapper<Dic>();
		queryWrapper.eq("`type`", "article");
		if(!StringUtils.isEmpty( enterpriseId)) {
			queryWrapper.eq("tenant_id", StringUtils.isEmpty( enterpriseId) ? "00000000" :  enterpriseId);
		}
		List<Dic> list = dicMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list);
	}

	@ApiOperation(value = "企业分类文章", notes = "")
	@GetMapping("/{enterpriseId}/article")
	public Result<PageInfo<Article>> enterpriseArticle(@PathVariable("enterpriseId") String enterpriseId,
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId,
			@ApiParam("") @RequestParam(value = "type", required = false) String type) {
		if(pageNum==null||pageSize==null) {
			pageNum=1;
			pageSize=10;
		}
		Page<Article> page = new Page<>(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
		QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("create_time");
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
		if (!StringUtils.isEmpty(tenantId)) {
			queryWrapper.eq("tenant_id", tenantId);
		}
		if (!StringUtils.isEmpty(type) && !"0".equals(type)) {
			queryWrapper.eq("type", type);
		}
		queryWrapper.select("id","title","title_image","`desc`","views","create_time");
		IPage<Article> info = articleMapper.selectPage(page, queryWrapper);
		PageInfo<Article> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	
	@ApiOperation(value = "记录文章学习时长", notes = "")
	@PostMapping("/article/watch/{articleId}/{countTime}")
	public Result<String> setCourseWatch(@PathVariable("articleId") String articleId,
			@PathVariable("countTime")int countTime,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		//QueryWrapper<Course> queryWrapperCourse = new QueryWrapper<Course>();
		//queryWrapperCourse.eq("course_id", courseId);
		//queryWrapperCourse.eq("user_id", loginInfo.getId());
		Article article = articleMapper.selectById(articleId);
		if (article == null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "该文章找不到！！！", null);
		}

		QueryWrapper<ArticleWatch> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("article_id", articleId);
		queryWrapper.eq("user_id", loginInfo.getId());
		List<ArticleWatch> watchs = articleWatchMapper.selectList(queryWrapper);
		int i = 0;
		if (watchs == null || watchs.size() == 0) {
			ArticleWatch entity = new ArticleWatch();
			entity.setCountTime(countTime);
			entity.setArticleId(articleId);
			entity.setUserId(loginInfo.getId());
			entity.setCreateTime(LocalDateTime.now());
			entity.setUpdateTime(LocalDateTime.now());
			
			i = articleWatchMapper.insert(entity);
		} else {
			ArticleWatch articleWatch = watchs.get(0);
			articleWatch.setUpdateTime(LocalDateTime.now());
			articleWatch.setCountTime(articleWatch.getCountTime() + countTime);
			i = articleWatchMapper.updateById(articleWatch);
		}

		return ResultUtil.data(i > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
				null);
	}
	
	
	
	
	public static int getMiao(){
		//long milliSecondsLeftToday = 86400000 - DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);
        long secondsLeftToday = 86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE);
        return (int)secondsLeftToday;
	}
}
